# Consul Agent (Upstart unit)
description "Consul Agent"

start on {{ consul_upstart_start_on }}
stop on {{ consul_upstart_stop_on }}

script
{% if consul_dynamic_bind %}
  # Get the public IP
  BIND=`ifconfig eth0 | grep "inet addr" | awk '{ print substr($2,6) }'`
{% endif %}

{% if consul_client_address_bind %}
  # Get the public IP
  CLIENT_BIND=`ifconfig eth0 | grep "inet addr" | awk '{ print substr($2,6) }'`
{% endif %}

  # Allow non-root to bind to privileged ports (if used)
  setcap CAP_NET_BIND_SERVICE=+eip {{ consul_home }}/bin/consul

  # Set GOMAXPROCS to use all our CPUs, because Consul can block a scheduler thread
  # Use su to become consul user non-interactively on old Upstart versions (see http://superuser.com/a/234541/76168)
  exec su -s /bin/sh -c 'GOMAXPROCS=`nproc` exec "$0" "$@" 1>> {{ consul_log_file }} &2>1' consul -- /opt/consul/bin/consul agent \
{% if consul_dynamic_bind %}
    -bind=$BIND \
{% endif %}
{% if consul_client_address_bind %}
    -client=$CLIENT_BIND \
{% endif %}
    -config-dir={{ consul_config_dir }} \
    -config-file={{ consul_config_file }}
end script

{% if consul_leave_on_terminate -%}
pre-stop exec {{ consul_home }}/bin/consul leave
{% endif -%}

respawn
respawn limit 10 10

# Avoid Upstart re-spawning the process upon `consul leave`
normal exit 0 INT

kill timeout 10
